// 卡片图标列表
const symbols = ['🍎', '🍌', '🍇', '🍓', '🍒', '🍍', '🥝', '🍉'];

// 游戏状态变量
let cards = [];
let firstCard = null;
let secondCard = null;

// 计时器
let seconds = 0;
let timerInterval = null;

// 步数统计
let moveCount = 0;

// 音效资源（使用你提供的路径）
const sounds = {
    match: new Audio('audio/success-game-alert.wav'),
    mismatch: new Audio('audio/losing-piano.wav'),
    win: new Audio('audio/winning.wav')
};

// 初始化游戏
function init() {
    firstCard = null;
    secondCard = null;
    moveCount = 0;
    seconds = 0;
    document.getElementById("moves").textContent = moveCount;
    document.getElementById("status").textContent = "";
    clearInterval(timerInterval);
    startTimer();

    const board = document.getElementById("game-board");
    board.innerHTML = "";

    const doubledSymbols = [...symbols, ...symbols];
    const shuffledSymbols = shuffle(doubledSymbols);

    shuffledSymbols.forEach(symbol => {
        const card = document.createElement("div");
        card.classList.add("card");
        card.dataset.symbol = symbol;
        card.textContent = "❓";
        card.addEventListener("click", flipCard);
        board.appendChild(card);
        cards.push(card);
    });
}

// 洗牌函数（Fisher-Yates）
function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

// 启动计时器
function startTimer() {
    seconds = 0;
    document.getElementById("timer").textContent = formatTime(seconds);
    timerInterval = setInterval(() => {
        seconds++;
        document.getElementById("timer").textContent = formatTime(seconds);
    }, 1000);
}

// 格式化时间 mm:ss
function formatTime(s) {
    const min = Math.floor(s / 60).toString().padStart(2, "0");
    const sec = (s % 60).toString().padStart(2, "0");
    return `${min}:${sec}`;
}

// 增加步数
function incrementMove() {
    moveCount++;
    document.getElementById("moves").textContent = moveCount;
}

// 翻牌事件处理（关键改进点）
function flipCard(e) {
    if (this.classList.contains("flipped")) return;

    this.textContent = this.dataset.symbol;
    this.classList.add("flipped");

    if (!firstCard) {
        firstCard = this;
    } else {
        secondCard = this;
        incrementMove();
        checkMatch();
    }
}

// 检查是否匹配
function checkMatch() {
    const card1 = firstCard;
    const card2 = secondCard;

    // 立即清空，允许用户继续点卡
    firstCard = null;
    secondCard = null;

    if (card1.dataset.symbol === card2.dataset.symbol) {
        playSound(sounds.match);
        // 成功匹配后移除点击事件
        card1.removeEventListener("click", flipCard);
        card2.removeEventListener("click", flipCard);
        checkWin();

    } else {
        playSound(sounds.mismatch);

        setTimeout(() => {
            card1.classList.remove("flipped");
            card2.classList.remove("flipped");
            card1.textContent = "❓";
            card2.textContent = "❓";
            checkWin();
        }, 600);
    }
}

// 播放音效（安全方式）
function playSound(sound) {
    if (sound) {
        sound.currentTime = 0;
        sound.play().catch(() => { });
    }
}

// 检查是否胜利
function checkWin() {
    const flippedCards = document.querySelectorAll(".card.flipped");
    if (flippedCards.length === cards.length) {
        playSound(sounds.win);
        clearInterval(timerInterval);
        document.getElementById("status").textContent = "🎉 恭喜你，全部配对成功！";
    }
}

// 重新开始按钮
document.getElementById("restart-btn").addEventListener("click", () => {
    cards = [];
    init();
});

// 页面加载后启动游戏
init();